//
//  LocationUtil.swift
//  Kool Car
//
//  Created by huangweiqiang on 2021/12/17.
//

import UIKit
import CoreLocation
///CLPlacemark 定位信息 NSInteger：结果 0 失败  1 成功
typealias LocationCallBack = (AnyObject, NSInteger) -> Void

class LocationUtil: NSObject {
    var locationCallBack: LocationCallBack!
    var locationManager: CLLocationManager!
    var resultDict: NSDictionary!
    
    //单例
    static let sharedInstance = LocationUtil()
    
    //MARK: -  开始定位
    //    授权状态为枚举值：
    //    kCLAuthorizationStatusNotDetermined                  //用户尚未对该应用程序作出选择
    //    kCLAuthorizationStatusRestricted                     //应用程序的定位权限被限制
    //    kCLAuthorizationStatusAuthorizedAlways               //一直允许获取定位
    //    kCLAuthorizationStatusAuthorizedWhenInUse            //在使用时允许获取定位
    //    kCLAuthorizationStatusAuthorized                     //已废弃，相当于一直允许获取定位
    //    kCLAuthorizationStatusDenied                         //拒绝获取定位
    func getUserLocation(complete: @escaping LocationCallBack) {
        self.locationCallBack = complete
        if CLLocationManager.locationServicesEnabled()  {
            if  CLLocationManager.authorizationStatus() == .denied ||
                    CLLocationManager.authorizationStatus() == .restricted {
                if self.locationCallBack != nil {
                    self.locationCallBack(NSDictionary.init(), 0)
                }
                return
            }
            self.locationManager = CLLocationManager.init()
            self.locationManager.delegate = self
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            self.locationManager.distanceFilter = 100
            self.locationManager.requestAlwaysAuthorization()
            self.locationManager.requestWhenInUseAuthorization()
            self.locationManager.startUpdatingLocation() //开始定位
        }else{
            //未开启定位
            if self.locationCallBack != nil {
//                self.locationCallBack(CLPlacemark.init(), 0)
               
            }
            return
        }
    }
}


extension LocationUtil: CLLocationManagerDelegate {
    //MARK: -  定位回调代理
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let currLocation = locations.last
        if currLocation == nil {
            return
        }
        self.locationManager.stopUpdatingLocation()
        let geoCoder = CLGeocoder.init() //反向解析，根据及纬度反向解析出地址
        geoCoder.reverseGeocodeLocation(currLocation!) { (placemarks, error) in
            if placemarks != nil {
                for place in (placemarks?.enumerated())! {
                    let resultDict = place.element //place.element.addressDictionary! as NSDictionary
                    if self.locationCallBack != nil {
                        self.locationCallBack(resultDict, 1)
                    }
                }
            }
        }
    }
    
    //MARK: -  检测应用是否开启定位服务
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        
        manager.stopUpdatingLocation()
        let err = error as! CLError
        switch err.code {
        case .denied:
            ()
        case .locationUnknown:
            ()
        default:
            ()
        }
    }
    
}
